/*
 * @Description: 拦截并处理跳转加载
 * @Author: Liu Kunpeng
 * @Date: 2021-07-05 20:41:06
 */
import router, { endRoutes } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, removeToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { filterAsyncRouter, getMenu } from '@/utils/page-auth'

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start() // 进度条

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in 获取token
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next()
      NProgress.done()// 结束Progress
    } else {
      const hasGetUserInfo = store.getters.username
       //如果有路由则直接下一步，如果没有则需要获取路由
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          await store.dispatch('user/getUserInfo') //异步存储用户信息
          await store.dispatch('user/getTreePermission') //异步存储用户权限
          var accessRoutes
          getMenu().then(res => {
            // console.log(res); //获得后端的副菜单栏内容
            accessRoutes = filterAsyncRouter(res) //路由过滤   前端动态路由的副菜单栏数组里若有res，就返回
            // console.log(accessRoutes); //匹配上了前端的router了
            var asyncRoutes = [...accessRoutes, ...endRoutes] //将endRoutes加上
            router.addRoutes(asyncRoutes)// 动态添加路由
            // console.log(router);  //router本身有7个
            router.options.routes = router.options.routes.concat(asyncRoutes) // 将路由数据传递给全局变量，做侧边栏菜单渲染工作
            
          })
          // get user info
          
          next()
        } catch (error) {
          // remove token and go to login page to re-login
          removeToken()
          Message.error({
            message: error || 'Has Error'
          })
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
